/**
    Copyright (C) 2012 Guido Ludwig

    This file is part of JATT.
	http://code.google.com/p/jatt/

    JATT is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package de.guidoludwig.jatt.util;

import java.util.Comparator;

public class ImageInfoComparator implements Comparator<ImageInfo> {

	private final int width;
	private final int minWidth;
	private final int maxWidth;
	private final long size;
	private final long minSize;
	private final long maxSize;

	public ImageInfoComparator(int width, long size) {
		this(width, 20, size, 20);
	}

	public ImageInfoComparator(int width, float widthVariance, long size,
			int sizeVariance) {
		this.width = width;
		this.size = size;

		minWidth = (int) (width * ((100 - widthVariance) / 100));
		maxWidth = (int) (width * ((100 + widthVariance) / 100));
		minSize = size * ((100 - sizeVariance) / 100);
		maxSize = size * ((100 + sizeVariance) / 100);
	}

	@Override
	public int compare(ImageInfo o1, ImageInfo o2) {
		if (o1 == null && o2 == null) {
			return 0;
		} else if (o1 == null) {
			return -1;
		} else if (o2 == null) {
			return 1;
		}
		boolean o1InVariance = inVariance(o1);
		boolean o2InVariance = inVariance(o2);
		if (o1InVariance && !o2InVariance) {
			return -1;
		} else if (o2InVariance && !o1InVariance) {
			return 1;
		}
		return malus(o1) - malus(o2);
	}

	private boolean inVariance(ImageInfo info) {
		int imgWidth = info.getWidth();
		if (minWidth > imgWidth || maxWidth < imgWidth) {
			return false;
		}
		long imgSize = info.getSize();
		if (minSize > imgWidth || maxSize < imgSize) {
			return false;
		}
		return true;
	}

	public int malus(ImageInfo info) {
		int malus = 0;
		int imgWidth = info.getWidth();
		if (imgWidth < width) {
			malus += (width - imgWidth) * 4;
		} else if (imgWidth > width) {
			malus += (imgWidth - width);
		}
		long imgSize = info.getSize();
		if (imgSize > size) {
			malus += (imgSize - size) / 1000;
		}
		return malus;

	}

}
